<template>
    <div class="have-footer loan-in-index">
        <div class="loan-in-index-wrapper have-footer wrapper" ref='content'>
            <div class="loan-in-index-box">
                <div class="banner-box">
                    <slide
                        key='in-banner'
                        v-if='bannerList.length'
                        swiperId='banner'
                        :loop='false'
                        :autoplay='5000'>
                        <div class='banner__item' v-for='item in bannerList' @click='goLink(item.redirectUrl)'>
                            <img :src="item.url">
                        </div>
                    </slide>
                    <div class="banner__item" v-show='loading_banner && !bannerList.length'>
                        <loading :size='15' mode='full'></loading>
                    </div>
                    <div class="chat" v-if='userInfo.user' @click.stop='goChat(userInfo.user.uuid)'>
                        <img src="../images/chat@3x.png">
                        <span class="unread" v-if='unreadNum'>{{unreadNum}}</span>    
                    </div>
                </div>
                
                <!-- message -->
                <div class="message borrow" v-if='messageList.length && messageShow' @click='goMessageDetail'>
                    <slide
                        swiperId='message'
                        direction='vertical'
                        :autoplay='2000'>
                        <div class="message__item" v-for='(item,index) in messageList' :data-index='index' :data-id='item.messageId'>
                            <span class='message__avatar'>
                                <img :src="item.user.avatar || placeholderImg" alt="">
                            </span>
                            <p class='message__text'>{{item.content}}</p>
                        </div>
                    </slide>
                    <i class="iconfont icon-close-pure" @click='messageShow = false'></i>
                </div>

                <div class="want-loan">
                    <div class="want-loan__button"><span class="button" @click="goLoanInWant">我要借款</span></div>
                    <div class="loan-index-mine-list" v-if='hasMain'>
                        <div class="loan-index-mine" 
                            v-if='main.myPublish.records && main.myPublish.records.length'
                            v-for='item in main.myPublish.records' 
                            @click='goLoanInDetailMe(item.borrowNo)'>
                            <div class='loan-index-mine__mid first'>
                                <p class='font-title'>{{ item.borrowAmount | toYuan }}元</p>
                                <span class='font-subhead'>{{ item.yearRate / 100 }}% | {{ item.borrowDays || placeholder }}{{item.daysTypeStr || placeholder}}</span>
                            </div>
                            <i class="iconfont icon-arrow"></i>
                        </div>
                    </div>
                    <div class="loan-index-mine-list">
                        <div class="loan-index-mine" @click='goRouter("loan-in-apply")'>
                            <img src="../images/w_borrow@3x.png">
                            <div class='loan-index-mine__mid'>我的借款记录</div>
                            <i class="iconfont icon-arrow"></i>
                        </div>
                    </div>
                </div>

                <div class="slogen">
                    <p class="slogen__item"> <img src="../images/user_slogen3.png"> <span>51信用卡战略投资</span></p>
                    <p class="slogen__item"> <img src="../images/user_slogen2.png"> <span>资料安全</span></p>
                    <p class="slogen__item"> <img src="../images/user_slogen1.png"> <span>信息真实</span></p>
                </div>
                <div class="recommend-list-title">
                    <img class='avatar' src="../images/avatar_lender@3x.png">
                    <p>TA们正在出借</p>
                </div>
                <template v-if='lendList.length'>
                    <div class="recommend-toolbar" ref='scrollDom'>
                        <span class="recommend-toobar__total">{{lendCount}}条记录</span>
                        <span v-show='!loading_switch' class="recommend-toolbar__switch" @click='switchRecommend("scroll","next")'>换一批</span>
                        <div v-show='loading_switch' class='recommend-filter-loading'><loading :size='12'></loading></div>
                    </div>
                    <div class="recommend-box">
                        <div class='recommend'>
                            <div class="recommend__item" v-for='item in lendList' @click='goRecommend(item)'>
                                <span class='recommend__lend-amount' v-if='item.lendNo'>{{item.lendAmountFrom | toYuanInt}} - {{item.lendAmountTo | toYuanInt}}元</span>
                                <span class='recommend__lend-amount' v-else>--</span>
                                <div class='mid' v-if='item.user'>
                                    <img :src="item.user.avatar || placeholderImg">
                                    <p>{{item.user.realName || placeholder}}</p>
                                    <img class='contact' v-if='item.isContact' width="16" height='16' src="../images/contactloan.png">
                                </div>
                                <div class='mid' v-else>
                                    <img :src="placeholderImg">
                                    <p>{{placeholder}}</p>
                                </div>
                                <i>找TA借</i>
                            </div>
                        </div>
                    </div>
                </template>
                <p class="page-placeholder" v-if='!lendList.length && !loading_switch'><span>暂无求借款记录</span></p>
                <div v-show='loading_switch' class='button pure'><loading mode='full' :size='12'></loading></div>
                <p v-show='lendList.length && !loading_switch && !lastPage' class='recommend-swtich-button button pure' @click='switchRecommend'>加载更多</p>
                <p v-show='lendList.length && !loading_switch && lastPage' class='recommend-swtich-text' @click='switchRecommend("scroll")'>
                    已经到底了，<span>换一批</span>再看看
                </p>
            </div>
        </div>

        
        <footer-bar></footer-bar>
    </div>
</template>

<script>
    import { Promise } from 'es6-promise'
    import dynamics from 'dynamics.js'
    import footerBar from '../components/FooterBar.vue'
    import selectGroup from '../components/SelectGroup.vue'
    import selectOption from '../components/SelectOption.vue'
    import radioGroup from '../components/RadioGroup.vue'
    import areaSelect from '../components/AreaSelect.vue'
    import radio from '../components/Radio.vue'
    import loading from '../components/Loading.vue'
    import checkBox from '../components/CheckBox.vue'
    import toolTip from '../components/ToolTip.vue'
    import modal from '../components/Modal.vue'
    import confirm from '../components/Confirm.vue'
    import buttonLoading from '../components/ButtonLoading.vue'
    import pagination from '../components/Pagination.vue'
    import payPassword from '../components/PayPassword.vue'
    import countDown from '../components/CountDown.vue'
    import slide from '../components/Slide.vue'
    import toYuan from '../filters/filter-toYuan'
    import booleanToStr from '../filters/filter-booleanToStr'
    import dateFormat from '../filters/filter-dateFormat'
    import toStar from '../filters/filter-toStar'
    import { convertRequestURL } from '../utils/utils'
    import  { mapGetters, mapActions }  from 'vuex'
    import { addLenderValidation, resetAccountPasswordValidation, operatorEditValidation } from '../validation/validation'
    import { contactApi, loanInApi, loanOutApi, messageApi } from '../api/api'
    import { scrollLoading, scrollLoadingOff } from '../utils/utils'
    import moment from 'moment'

    export default {
        components:{
            footerBar,
            selectGroup,
            selectOption,
            radioGroup,
            radio,
            checkBox,
            areaSelect,
            loading,
            toolTip,
            modal,
            confirm,
            slide,
            buttonLoading,
            pagination,
            payPassword,
            countDown,
        },
        filters:{
            toYuan,
            toStar,
            booleanToStr,
            dateFormat,
            diffDay(time){
                let now = moment()
                let day = moment(time)
                let diff = day - now
            },
            toYuanInt(money){
                if(money === 0) return '0'
                else if(!money) return '0'
                else if(money >= 1000000){
                    return Number((money/1000000).toFixed(2)) + '万'
                }
                else return Number((money/100).toFixed(2))
            }

        },
        data() {
            return {
                main:{},
                currentPage:'',
                totalPage:'',
                totalCount:'',
                placeholderImg:require('../images/loading_1.png'),
                currentImg:'',
                borrowInfo:'',
                pageLoaded:false,
                currentText:'',
                payPasswordShow:false,
                messageShow:true,
                loading_switch:false,
                messageList:[],
                bannerList:[],
                messageIndex:0,
                payStatus:'',
                recommend:[],
                password:'',
                placeholder:'--',
                userCount:'',
                listInfo:{},
                records:[],
                loading:true,
                loading_banner:true,
                loading_count:true,
            }
        },
        computed:{
            ...mapGetters([
                'msgTip',
                'localInfo',
            ]),
            scrollIn(){
                return this.localInfo.scrollIn
            },
            unreadNum(){
                return this.localInfo.unreadNum
            },
            lendList(){
                return this.localInfo.lendList
            },
            lendCount(){
                if(this.localInfo.lendPageInfo.outPageInfo)
                return this.localInfo.lendPageInfo.outPageInfo.totalCount
            },
            lendPageInfo(){
                return this.localInfo.lendPageInfo
            },
            lendCount(){
                if(this.localInfo.lendPageInfo.outPageInfo)
                return this.localInfo.lendPageInfo.outPageInfo.totalCount
            },
            lastPage(){
                if(this.localInfo.lendPageInfo.inPageInfo)
                return this.localInfo.lendPageInfo.inPageInfo.totalPage == this.localInfo.lendPageInfo.inPageInfo.pageNum
            },
            currentOutPage(){
                if(this.localInfo.lendPageInfo.outPageInfo)
                return this.localInfo.lendPageInfo.outPageInfo.pageNum
            },
            currentPage(){
                if(_.isEmpty(this.listInfo)) return 1
                return this.listInfo.pageNum
            },
            channel(){
                return this.localInfo.channel
            },
            userInfo(){
                return this.localInfo.userInfo
            },
            hasMain(){
                return !_.isEmpty(this.main)
            },
            allEmpty(){
                if(_.isEmpty(this.main)){
                    return true
                }
                else{
                    let len1 = this.main.applyToMe.records.length
                    let len2 = this.main.myApply.records.length
                    let len3 = this.main.myPublish.records.length
                    let len4 = this.main.otherPublish.records.length

                    if(!len1 && !len2 && !len3 && !len4 ){
                        return true
                    }
                }
                return false
            },
            needLogin(){
                return this.localInfo.needLogin
            },
        },
        methods:{
            // actions
            ...mapActions([
                'showLoading',
                'hideLoading',
                'setMsgTip',
                'setShare',
                'showShare',
                'lendListSquare',
                'setScrollIn'
            ]),

            // function
            daysTransform(days){

                let str
                if(days >= 30){
                    str = days / 30 + '个月'

                }
                else{
                    str = days + '天'
                }
                return str
                
            },

            goLink(url){
                if(!this.checkLogin()) return
                if(!url) return
                location.href = url
            },
            goChat(id){

                if(!this.userInfo.isPay || this.userInfo.isExpired){
                    this.setMsgTip({
                        text:'请先完成信用报告',
                        type:'info'

                    })
                    this.$router.push({
                        name:'user-credit-report-index'
                    })
                    return
                }
                if(this.userInfo.user){
                    if(!this.userInfo.user.bizRole){
                        this.$router.push({
                            name:'id-select'
                        })
                        return false
                    }
                }
                
                this.showLoading()
                contactApi.im({
                    uuid:id
                })
                .then(result=>{
                    this.hideLoading()
                    let info = result.info
                    let myAccid = info.myAccid
                    let accid = info.accid
                    let token = info.token
                    location.href = convertRequestURL(`?token=${token}&uid=${myAccid}#/session`,'chat')
                })
                .catch(error => {
                    console.error(error)
                    this.hideLoading()
                })
            },
            withinOneDay(time){
                let now = moment()
                let diff = moment(time)
                let diffDays = diff.diff(now,'days')
                let diffTime = diff.diff(now)
                if(diffDays <= 0) return true
                return diffDays
                return true
            },
            goLoanInDetailMe(number,lendNo){
                this.$router.push({
                    name:'loan-in-detail-me',
                    params:{
                        number:number
                    },
                    query:{
                        lendNo:lendNo
                    }
                })
            },
            goLoanInDetailOther(number){
                this.$router.push({
                    name:'loan-in-detail-other',
                    params:{
                        number:number
                    }
                })
            },
            goRecommend(item){
                if(!this.checkLogin()) return
                    
                this.$ga.event({
                  eventCategory: 'link',
                  eventAction: 'click',
                  eventLabel: 'borrowRecommend - ' + this.channel + '-' + item.user.realName
                })

                let user = item.user
                this.$router.push({
                    name:'contact-detail',
                    params:{
                        id:user.uuid,
                    },
                    query:{
                        type:'lend'
                    }
                })
            },
            share(item){
                let protocol = location.protocol
                let host = location.host
                let pathname = location.pathname
                let search = location.search

                let realUrl = `${protocol}//${host}${pathname}${search}#share-loan-in/${item.borrowNo}`
                this.setShare({
                    message:{
                        title: '安牛有借，海量客户，一键拓客', // 分享标题
                        desc: `金额: ${toYuan(item.borrowAmount)},时长: ${dateFormat(item.createdAt)}- ${dateFormat(item.borrowEffectiveTime)}, 利率: ${(item.yearRate / 100).toFixed(2)}%, 用途: ${item.borrowUsage}`, // 分享描述
                        link: realUrl, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                        imgUrl: 'https://youjie.kongapi.com/pic/loading_1.png', // 分享图标
                        type: '', // 分享类型,music、video或link，不填默认为link
                        dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
                        success: function () { 

                        },
                        cancel: function () { 

                        }
                    },
                    timeline:{
                        title: '安牛有借，海量客户，一键拓客', // 分享标题
                        link: realUrl, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                        imgUrl: 'https://youjie.kongapi.com/pic/loading_1.png', // 分享图标
                        success: function () { 
                            
                        },
                        cancel: function () { 

                        }
                    },
                    qq:{
                        title: '安牛有借，海量客户，一键拓客', // 分享标题
                        desc: `金额: ${toYuan(item.borrowAmount)},时长: ${dateFormat(item.createdAt)}- ${dateFormat(item.borrowEffectiveTime)}, 利率: ${(item.yearRate / 100).toFixed(2)}%, 用途: ${item.borrowUsage}`, // 分享描述
                        link: realUrl, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                        imgUrl: 'https://youjie.kongapi.com/pic/loading_1.png', // 分享图标
                        success: function () { 
                            
                        },
                        cancel: function () { 

                        }
                    },
                })
                this.showShare()
            },
            goRouter(name){
                if(!this.checkLogin()) return

                this.$router.push({
                    name:name
                })
            },
            goLoanInWant(){
                if(!this.check()) return
                
                this.$router.push({
                    name:'loan-in-want-index',
                    params:{
                        number:'default'
                    }
                })
            },
            goMessageDetail(event){
                let el = $(event.target).closest('.swiper-slide')
                if(!el.length) return

                let id = el.data('id')

                this.$router.push({
                    name:'message-box-detail',
                    params:{
                        id:id
                    }
                })
            },
            checkLogin(){
                if(this.needLogin){
                    this.$router.push({
                        name:'bind-phone'
                    })
                    return false
                }
                if(this.userInfo.user){
                    if(!this.userInfo.user.bizRole){
                        this.$router.push({
                            name:'id-select'
                        })
                        return false
                    }
                }
                return true
            },
            check(){
                if(this.needLogin){
                    this.$router.push({
                        name:'bind-phone'
                    })
                    return false
                }
                if(this.userInfo.user){
                    if(!this.userInfo.user.bizRole){
                        this.$router.push({
                            name:'id-select'
                        })
                        return false
                    }
                }
                if(this.hasMain){
                    if(this.main.myPublish.records.length){
                        this.setMsgTip({
                            text:'有正在发布的借款，请勿重复发布',
                            type:'warn'
                        })
                        return false
                    }
                }
                return true
            },
            goDetailMe(){
            },
            goPay(){
                this.payStatus = true
                console.log(1)
            },
            goLoanOutDetailOther(user){
                this.$router.push({
                    name:'loan-out-detail-other',
                    params:{
                        id:user.uuid,
                    },
                    query:{
                        type:'add'
                    }
                })
            },
            goDetail(item){
                this.$router.push({
                    name:'user-detail',
                    params:{
                        id:item.userId,
                    }
                })
            },
            getMain(){
                this.showLoading()
                loanInApi.main()
                .then(result=>{
                    this.main = result
                    this.pageLoaded=true
                    this.hideLoading()
                })
                .catch(error => {
                    console.error(error)
                    this.pageLoaded=true
                    this.hideLoading()
                })
            },
            getMessage(){
                messageApi.unReadList()
                .then(result=>{

                    this.messageList = result
                })
                .catch(error => {
                    console.error(error)
                })
            },
            getMyBorrowPublishing(){
                loanInApi.myBorrowPublishing()
                .then(result=>{
                    this.borrowInfo = result
                })
                .catch(error => {
                    console.error(error)
                })
            },
            getBanner(){
                loanInApi.banner({
                    bizRole:'C'
                })
                .then(result=>{
                    this.loading_banner = false
                    this.bannerList = result
                })
                .catch(error => {
                    this.loading_banner = false
                    console.error(error)
                })
            },
            getRecommend(num){
                if(!this.lendList.length){
                    this.loading_switch = true
                    this.lendListSquare({
                        pageNum:this.currentOutPage + 1,
                        action:'next'
                    })
                    .then(result=>{
                        this.loading_switch = false

                    })
                    .catch(error => {
                        console.error(error)
                        this.loading_switch = false
                    })
                }
            },
            switchRecommend(type,action){
                this.loading_switch = true
                let scrollTop = $(this.$refs.content).scrollTop()
                let top = scrollTop + $(this.$refs.scrollDom).offset().top
                let object = {}
                if(type == 'scroll' && action == 'next'){
                    object = {
                        pageNum:this.currentOutPage + 1,
                        action:'next'
                    }
                }
                this.lendListSquare(object)
                .then(result=>{
                    this.loading_switch = false
                    if(type == 'scroll'){
                        let o = {
                          scroll: scrollTop
                        }

                        // $('body').css('visibility','hidden')

                        dynamics.animate(o, {
                          scroll: top,
                        }, {
                          change: ()=> {
                            $(this.$refs.content).scrollTop(o.scroll);
                          },
                          type: dynamics.easeInOut,
                          duration: 500,
                          friction: 50
                        })
                        // $('body').css('visibility','visible')
                    }
                })
                .catch(error => {
                    console.error(error)
                    this.loading_switch = false
                })
            }
        },
        created(){
            let userInfo = this.userInfo
            let user = userInfo && userInfo.user
            let bizRole = user && user.bizRole
            console.log(bizRole)
            if(bizRole == "B"){
                this.$router.replace({
                    name:'loan-out-index'
                })
                return
            }
            this.getMain()
            this.getBanner()
            this.getMessage()
            this.getRecommend(1)
            this.$nextTick(()=>{
                $(this.$refs.content).scrollTop(this.scrollIn);
                scrollLoading('.loan-in-index-wrapper','.loan-in-index-box',()=>{
                    if(this.lastPage) return
                    this.switchRecommend()
                },110)
            })
        },
        destroyed(){
            scrollLoadingOff('.loan-in-index-box')
            let scrollTop = $('.loan-in-index-wrapper').scrollTop()
            this.setScrollIn(scrollTop)
        }
    }
</script>

<style lang="scss">
    @import "../sass/variables";
    @import "../sass/extends";
    @import "../sass/mixins";
    .loan-in-index{
        .loan-index-mine{
            display: flex;
            align-items: center;
            justify-content: space-between;
            .loan-index-mine__mid{
                display: flex;
                align-items: center;
                &.first{
                    padding-left: 0;
                }
                .font-title{
                    padding-right: 8px;
                }
            }  
        }
        .recommend{
            padding:0 16px;
        }
        .recommend__item{
            float:none;
            width: 100%;
        }
        .card-want-loan{
            margin-top: 16px;
            padding: 16px;
        }
        .fundraising-info{
            color:rgba(#000,.54);
            .font-body1{
                color:$orange;
            }
            .font-caption{
                display: flex;
            }
        }
        .want-loan{

        }
        .want-loan__text{
            @extend %font-caption;
            padding-top: 6px;
            text-align: center;
        }
        .apply-button{
            border-top: 1px solid $sectionColor;
            margin-top: 22px;
            padding: 8px;
        }
        .placeholder{
            padding-top: 48px;
            text-align: center;
            p{
                @extend %font-caption;
                padding-top: 6px;
            }
        }
        .recommend-toolbar__switch{
            @extend %font-button;
            line-height:48px;
            color:$orange;
            padding:0 16px;
        }
        .recommend-swtich-text{
            @extend %font-body1;
            line-height:36px;
            text-align:center;
            span{
                @extend %font-body2;
                color:$orange;
            }
        }
    }

</style>
